package com.tian.core.utils;

import cn.hutool.core.date.DateUtil;
import com.tian.core.exceptions.CheckException;
import com.tian.core.lang.ErrorDefine;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件工具类
 * @author YangTao
 * @date 2025/4/18
 */
public class FileUtil extends cn.hutool.core.io.FileUtil{

    /**
     * 上传多个文件
     * @param files
     * @param configPath
     * @return
     */
    public static List<String> uploadFile(MultipartFile[] files, String configPath) {
        List<String> urls = new ArrayList<>();
        for(MultipartFile file : files) {
            urls.add(uploadFile(file,configPath));
        }
        return urls;
    }

    /**
     * 上传文件
     *
     * @param file       file对象
     * @param configPath 配置文件中的路径
     * @return 保存在服务器上的url
     */
    public static String uploadFile(MultipartFile file, String configPath) {
        CommonsMultipartFile file1 = (CommonsMultipartFile) file;
        String importFileName = file1.getFileItem().getName();
        String savePath = getSavePath(configPath);
        File saveFile = getSaveFile(savePath,importFileName);
        try {
            FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
        } catch (IOException e) {
            throw new CheckException(ErrorDefine.FILE_UPLOAD_ERROR_MSG);
        }
        return saveFile.getPath();
    }

    /**
     * 获取存储的路径
     * @param configPath
     * @return
     */
    public static String getSavePath(String configPath) {
        Date date = DateUtil.date();
        String year = DateUtil.year(date)+"";
        String month = (DateUtil.month(date)+1)+"";
        String day = DateUtil.dayOfMonth(date)+"";
        StringBuffer filePath = new StringBuffer(configPath);
        filePath.append("/").append(year);
        filePath.append("/").append(month);
        filePath.append("/").append(day);
        return filePath.toString();
    }

    /**
     * 获取保存的文件(空文件)
     * @param savePath
     * @param importFileName
     * @return
     */
    private static File getSaveFile(String savePath, String importFileName){
        File file = new File(savePath + "/" + importFileName);
        // 如果有相同名称的文件则新建一个当前毫秒数的文件夹
        if (file.exists()) {
            long timeMillis = System.currentTimeMillis();
            file = new File(savePath + "/" + timeMillis);
            boolean success = file.mkdirs();
            if (success) {
                file = new File(savePath + "/" + timeMillis + "/" + importFileName);
            }else{
                throw new CheckException(ErrorDefine.FILE_UPLOAD_ERROR_MSG);
            }
        }
        return file;
    }
}
